<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<div id="appRole">
<el-row>
<el-col :span="24">
	<el-breadcrumb separator-class="el-icon-arrow-right">
		<el-breadcrumb-item>首页</el-breadcrumb-item>
		<el-breadcrumb-item>用户与权限</el-breadcrumb-item>
		<el-breadcrumb-item>角色管理</el-breadcrumb-item>
	</el-breadcrumb>
</el-col>
</el-row>
<el-row>
<el-col :span="24"align="right">
	<el-button @click="handleAddRole" size="small" type="success" icon="el-icon-circle-plus-outline">添加角色</el-button>
</el-col>
</el-row>
<br>
<el-row>
<el-col :span="24">
	<el-table ref="tableRole" :data="tableRoleData" border stripe fit highlight-current-row
		v-loading="tableRoleLoading" max-height="1200">
	    <el-table-column type="index" label="序号" :index="indexMethod" width="80">
	    </el-table-column>
		<el-table-column prop="name" label="角色名称" width="120">
		</el-table-column>
		<el-table-column prop="roleDesc" label="描述" width="360" :show-overflow-tooltip="true">
		</el-table-column>
		<el-table-column prop="created" label="创建日期" :formatter="dateFormat" width="180" sortable>
		</el-table-column>
		<el-table-column prop="updated" label="修改日期" :formatter="dateFormat" width="180" sortable>
		</el-table-column>
	    <el-table-column label="操作" width="180">
			<template slot-scope="scope">
				<el-button @click="handleEditRole(scope.$index, scope.row)" type="text" size="small">编辑</el-button>
				<el-button @click="handleSetRight(scope.$index, scope.row)" type="text" size="small">指定权限</el-button>
			</template>
	    </el-table-column>
	</el-table>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
	<el-pagination
		@size-change="handleSizeChange"
		@current-change="handleCurrentChange"
		:current-page="page"
		:page-sizes="[1, 10, 20, 50, 100]"
		:page-size="20"
		layout="total, sizes, prev, pager, next, jumper"
		:total="total">
	</el-pagination>
</el-col>
</el-row>

<el-dialog :title="dialogRoleTitle" :visible.sync="dialogRoleVisible" width="600px" @closed="dialogRoleClosed">
	<el-form ref="formRole" :model="modelRole" status-icon :rules="rulesUser">
		<el-form-item label="角色名称" :label-width="formRoleLabelWidth" prop="name">
			<el-input v-model="modelRole.name" autocomplete="off" maxlength="50"></el-input>
		</el-form-item>
		<el-form-item label="描述" :label-width="formRoleLabelWidth" prop="roleDesc">
			<el-input v-model="modelRole.roleDesc" autocomplete="off" maxlength="100" type="textarea" :rows="2"></el-input>
		</el-form-item>
	</el-form>
	<div slot="footer" class="dialog-footer">
		<el-button @click="dialogRoleVisible = false">取 消</el-button>
		<el-button type="primary" :loading="isButtonLoadingRole" @click="onSubmitRole">确 定</el-button>
	</div>
</el-dialog>

<el-checkbox-group v-model="checksSetRight">
<el-dialog :title="dialogSetRightTitle" :visible.sync="dialogSetRightVisible" width="950px" @closed="dialogSetRightClosed">
	<el-tree :data="dataSetRight" default-expand-all node-key="id" ref="treeSetRight" highlight-current 
		:props="defaultProps"
		:expand-on-click-node="false">
		<span class="custom-tree-node" slot-scope="{ node, data }">
			<span>{{ node.label }}</span>
			&nbsp;&nbsp;&nbsp;&nbsp;
	        <span>
	        	<el-checkbox v-for="rightKind in dataRightKindList" 
	        		:label="getRightId(data.id, rightKind.kind)"  :key="getRightId(data.id, rightKind.kind)"
	        		v-if="checkRightVisible(data.id, rightKind.kind)">{{rightKind.name}}</el-checkbox>
	        </span>
		</span>
	</el-tree>
	<div slot="footer" class="dialog-footer">
		<el-button @click="dialogSetRightVisible = false">取 消</el-button>
		<el-button type="primary" :loading="isButtonLoadingSetRight" @click="onSubmitSetRight">确 定</el-button>
	</div>
</el-dialog>
</el-checkbox-group>
</div>

<script>
	var appRole = new Vue({
		el: '#appRole',
		data() {
			var checkName = (rule, value, callback) => {
		        if (!value) {
		          return callback(new Error('角色名称不能为空'));
		        } else {
		        	callback();
		        }
			};
			var checkRoleDesc = (rule, value, callback) => {
		        if (!value) {
		          return callback(new Error('描述不能为空'));
		        } else {
		        	callback();
		        }
			};
			return {
				urlPostRoleList: '/api/role/list',
				urlPostRoleSave: '/api/role/save',
				urlPostMenuTree: '/api/menu/tree',
				urlPostRightList: '/api/right/list',
				urlGetRoleRight: '/api/role/right/',
				urlPostSetRight: '/api/role/setright',
				page: 1,
				rows: 20,
				total: 100,
				tableRoleData: [],
				tableRoleLoading: false,
				dialogRoleVisible: false,
				dialogRoleTitle: '添加角色',
				modelRole: {
					id: null,
		            name: '',
		            roleDesc: ''
		          },
				rulesUser: {
					name: [{validator: checkName, trigger: 'blur'}],
					roleDesc: [{validator: checkRoleDesc, trigger: 'blur'}]
				},
				formRoleLabelWidth: '70px',
				isButtonLoadingRole: false,
				roleIdSetRight: null,
				dialogSetRightTitle: '指定权限',
				dialogSetRightVisible: false,
				isButtonLoadingSetRight: false,
				dataSetRight: [],
		        defaultProps: {
					children: 'children',
					label: 'name'
				},
				checksSetRight: [202, 303],
				dataRightList: [],
				dataRightKindList: []
			}
		},
		methods: {
			/* Table */
			loadtableRoleData() {
				this.tableRoleLoading = true;
				this.$http.post(this.urlPostRoleList, {page: this.page, rows: this.rows}, {emulateJSON: true}).
				then(function(response) {
					if (response.body.status == 200) {
						this.tableRoleData = response.body.data.list;
						this.total = response.body.data.total;
						this.tableRoleLoading = false;
					}
				}).catch(function (error) {
					console.log(error);
				});	
			},
			handleSizeChange(val) {
				console.log('每页' + val + '条');
				this.rows = val;
				this.loadtableRoleData();
			},
			handleCurrentChange(val) {
				console.log('当前页:' + val);
				this.page = val;
				this.loadtableRoleData();
			},
			handleAddRole() {
				this.dialogRoleTitle = '添加角色';
				this.dialogRoleVisible = true;
			},
			handleEditRole(index, row) {
				console.log(index, row);
				//this.$message(row.id + '');
				this.dialogRoleTitle = '修改角色';
				this.dialogRoleVisible = true;
				this.modelRole.id = row.id;
				this.modelRole.name = row.name;
				this.modelRole.roleDesc = row.roleDesc;
			},
			indexMethod(index) {
				return index + 1;
			},
			dateFormat(row, column, cellValue, index) {
				var date = new Date(cellValue);
				return formatDate(date, "yyyy-MM-dd hh:mm:ss");
			},
			/* Edit */
			onSubmitRole() {
				this.isButtonLoadingRole = true;
				this.$refs.formRole.validate((valid) => {
					if (valid) {
						this.$refs.formRole.$http.post(this.urlPostRoleSave, this.modelRole, {emulateJSON: true})
						.then(function (response) {
							if (response.body.status == 200) {
								this.$message({
									message: "保存成功",
									type: "success"
								});
								appRole.isButtonLoadingRole = false;
								appRole.dialogRoleVisible = false;								
								appRole.loadtableRoleData();
							} else {
								this.$message.error(response.body.msg);
								appRole.isButtonLoadingRole = false;
							}
						}).catch(function (error) {
							console.log(error);
						});							
					}
				});
			},
			resetForm() {
				this.modelRole = {
						id: null,
			            username: '',
			            phone: '',
			            email: '',
			            status: 1
				};
				this.$refs.formRole.resetFields();
			},
			dialogRoleClosed() {
				this.resetForm();
			},
			/* Right */
			dialogSetRightClosed() {
				this.checksSetRight = [];
			},
			handleSetRight(index, row) {
				this.dialogSetRightTitle = '为角色【' + row.name + '】指定权限';
				this.roleIdSetRight = row.id;
				this.dialogSetRightVisible = true;
				this.$http.get(this.urlGetRoleRight + row.id).then(function(response) {
					if (response.body.status == 200) {
						this.checksSetRight = response.body.data;
						this.dialogSetRightVisible = true;
					}
    			}).catch(function (error) {
					console.log(error);
				});
			},
			loadDataSetRight() {
				if (JSON.stringify(this.dataSetRight) === '[]') {
					this.$http.post(this.urlPostMenuTree, null, {emulateJSON: true})
					.then(function (response) {
						if (response.body.status == 200) {
							this.dataSetRight = response.body.data;
						}
					}).catch(function (error) {
						console.log(error);
					});
				}
			},
			loadDataRightList() {
				if (JSON.stringify(this.dataRightList) === '[]') {
					this.$http.post(this.urlPostRightList, null, {emulateJSON: true})
					.then(function(response) {
						if (response.body.status == 200) {
							this.dataRightList = response.body.data;
							// 提取RightKindList
							this.dataRightList.forEach((item)=>{
								var existed = false;
								for (var i = 0; i < this.dataRightKindList.length; i++) {
									if (item.kind == this.dataRightKindList[i].kind) {
										existed = true;
										break;
									}
								}
								if (!existed) {
									this.dataRightKindList.push({kind: item.kind, name: item.name});
								}
							});
						}
	    			}).catch(function (error) {
						console.log(error);
					});
				}
			},
			checkRightVisible(menuId, rightKind) {
				var flag = false;
				for (var i = 0; i < this.dataRightList.length; i++) {
					if (this.dataRightList[i].menuId == menuId && this.dataRightList[i].kind == rightKind) {
						flag = true;
						break;
					}
				}
				return flag;
			},
			getRightId(menuId, rightKind) {
				for (var i = 0; i < this.dataRightList.length; i++) {
					if (this.dataRightList[i].menuId == menuId && this.dataRightList[i].kind == rightKind) {
						var rightId = this.dataRightList[i].id;
						return rightId;											
					}
				}
			},
			onSubmitSetRight() {		
				this.isButtonLoadingSetRight = true;
				this.$http.post(this.urlPostSetRight, {roleId: this.roleIdSetRight, rightIds: this.checksSetRight.join(',')}, {emulateJSON: true})
				.then(function (response) {
					if (response.body.status == 200) {
						this.isButtonLoadingSetRight = false;
						this.dialogSetRightVisible = false;
					} else {
						this.$message.error(response.body.msg);
					}
				}).catch(function (error) {
					console.log(error);
				});
			}
		},
		created() {
			this.loadtableRoleData();
			this.loadDataSetRight();
			this.loadDataRightList();
		}
	})
</script>